package com.after.saas.file.controller;

import cn.hutool.core.io.FileUtil;
import com.after.saas.common.constants.Result;
import com.after.saas.common.exception.BaseException;
import com.after.saas.common.model.vo.ValidBeanVO;
import com.after.saas.common.utils.ResponseUtil;
import com.after.saas.common.validate.Group;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.groups.Default;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
@RestController
@Api(tags = "文件上传")
public class UploadController {

    @PostMapping(value = "/upload")
    @ApiOperation(value = "单文件上传文件")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        saveFile(file, FileUtil.getUserHomePath());
        return ResponseUtil.SUCCESS();
    }

    @PostMapping(value = "/uploads")
    @ApiOperation(value = "多文件上传文件")
    public Result<String> uploads(@RequestParam("file") MultipartFile[] files) {
        String savePath = FileUtil.getUserHomePath();
        for (MultipartFile file : files) {
            saveFile(file, savePath);
        }
        return ResponseUtil.SUCCESS();
    }

    public void saveFile(MultipartFile file, String savePath) {
        if (!file.isEmpty()) {
            try {
                File targetFile = new File(savePath, file.getOriginalFilename());
                file.transferTo(targetFile);
            } catch (Exception e) {
                log.error(e.getMessage());
                throw new BaseException("文件上传失败！" + e.getMessage());
            }
        }
    }

    @PostMapping("/valid")
    public Result<String> testValid(@Validated({Default.class, Group.AddGroup.class}) @RequestBody ValidBeanVO validBeanVO) {
        return ResponseUtil.SUCCESS();
    }
}
